import env from '../config/index.js';
import { Muster } from '@/types/utils';
class Cache {
  name = "";
  expiredKey = "_expired_time";
  // 过期时间的倍数
  expiredCount = 1000 * 60;
  constructor(name: string) {
    this.name = name;
  }
  // 过期时间戳计算
  expiredCompute(time: number) {
    return time * this.expiredCount + new Date().getTime();
  }
  // 设置缓存过期时间
  setExpiredTiem<P>(cache: Muster, key: string, payload: P, time: number) {
    cache[key] = new Object();
    cache[key]["data"] = payload;
    cache[key][`${key}${this.expiredKey}`] = this.expiredCompute(time);
  }
  // 是否过期
  isExpired(expiredTiem: number) {
    let nowTime = new Date().getTime();
    return nowTime >= expiredTiem;
  }
  // 设置缓存
  setItem<P>(key: string, payload: P, expiredTiem = 0) {
    let cache = this.toObject(this.getItem(this.name)) || {};
    if (key == this.name) {
      cache = payload;
    } else {
      if (expiredTiem) {
        this.setExpiredTiem(cache, key, payload, expiredTiem);
      } else {
        cache[key] = payload;
      }
    }
    uni.setStorageSync(this.name, cache);
  }
  parse<D>(data: D) {
    return typeof data == "string" ? JSON.parse(data) : data;
  }
  // 获取缓存
  getItem(key: string) {
    let rootCache = uni.getStorageSync(this.name);
    if (key == this.name) return rootCache;
    let cache = rootCache[key];

    if (
      typeof cache == "object" &&
      cache.hasOwnProperty(`${key}${this.expiredKey}`)
    ) {
      if (this.isExpired(cache[`${key}${this.expiredKey}`])) {
        this.removeItem(key);
        delete cache["data"];
      }
      return this.parse(cache["data"]);
    }
    return this.parse(cache);
  }
  toObject(cache: Muster) {
    return cache && typeof cache == "string" ? JSON.parse(cache) : cache;
  }
  // 删除缓存
  removeItem(key: string) {
    if (this.name == key) {
      uni.removeStorageSync(this.name);
    } else {
      let cache = this.getItem(this.name);
      delete cache[key];
      this.setItem(this.name, cache);
    }
  }
}

export default new Cache(env.appName);